<template>
  <div class="basic-info">
    <h2>基本信息</h2>
    <el-form :model="form" label-width="120px">
      <el-form-item label="头像">
        <el-upload
            class="avatar-uploader"
            action="http://localhost:8080/api/v1/upload"
            :show-file-list="false"
            :data="{ type: 'avatar' }"
            :before-upload="beforeAvatarUpload"
            :on-success="handleAvatarSuccess"
            :on-error="handleAvatarError"
            name="files"
            accept="image/*">
          <img v-if="form.avatarUrl" :src="getFullImageUrl(form.avatarUrl)" class="avatar">
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="姓名">
        <el-input v-model="form.realName"></el-input>
      </el-form-item>
      <el-form-item label="性别">
        <el-radio-group v-model="form.gender">
          <el-radio :label="1">男</el-radio>
          <el-radio :label="2">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="出生日期">
        <el-date-picker
            v-model="form.birthDate"
            type="date"
            placeholder="选择日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="联系电话">
        <el-input v-model="form.phone"></el-input>
      </el-form-item>
      <el-form-item label="电子邮箱">
        <el-input v-model="form.email"></el-input>
      </el-form-item>
      <el-form-item label="居住地址">
        <el-input v-model="form.address"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import axios from 'axios'

const BASE_URL = 'http://localhost:8080'

const form = ref({
  avatarUrl: '',
  realName: '',
  gender: 1,
  birthDate: '',
  phone: '',
  email: '',
  address: ''
})

// 获取完整图片URL
const getFullImageUrl = (url) => {
  if (!url) return ''
  if (url.startsWith('http')) return url
  return `${BASE_URL}${url.startsWith('/') ? '' : '/'}${url}`
}

const userStr = localStorage.getItem('user');
if (!userStr) {
  throw new Error('未获取到用户信息');
}

const userData = JSON.parse(userStr);
const username = userData.user.username;

onMounted(async () => {
  try {
    const res = await axios.get(BASE_URL+'/api/volunteer/userInfo', {
      params: { username }
    })
    if (res.data && res.data.data) {
      form.value = {
        ...form.value,
        avatarUrl: res.data.data.avatarUrl || '',
        realName: res.data.data.realName || '',
        gender: res.data.data.gender || 1,
        birthDate: res.data.data.birthDate || '',
        phone: res.data.data.phone || '',
        email: res.data.data.email || '',
        address: res.data.data.address || ''
      }
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败')
  }
})

const handleAvatarSuccess = (response) => {
  console.log('完整上传响应:', response) // 调试日志

  // 情况1：后端返回的是 {urls: ["/avatar/xxx.png"]} 格式
  if (response && response.urls && Array.isArray(response.urls) && response.urls.length > 0) {
    form.value.avatarUrl = response.urls[0];
    ElMessage.success('头像上传成功');
    return;
  }

  // 情况2：直接返回文件路径字符串
  if (typeof response === 'string') {
    form.value.avatarUrl = response;
    ElMessage.success('头像上传成功');
    return;
  }

  // 情况3：返回对象格式 { data: "path" }
  if (response && response.data) {
    form.value.avatarUrl = response.data;
    ElMessage.success('头像上传成功');
    return;
  }

  // 情况4：Spring ResponseEntity包装的响应
  if (response && response.body) {
    const body = response.body;
    if (typeof body === 'string') {
      form.value.avatarUrl = body;
    } else if (body.data) {
      form.value.avatarUrl = body.data;
    } else if (body.urls && Array.isArray(body.urls) && body.urls.length > 0) {
      form.value.avatarUrl = body.urls[0];
    }
    ElMessage.success('头像上传成功');
    return;
  }

  ElMessage.warning('头像上传成功，但未获取到返回的URL');
  console.error('无法解析的上传响应:', response);
}

const beforeAvatarUpload = (file) => {
  const isValidType = ['image/jpeg', 'image/png'].includes(file.type);
  const isValidSize = file.size / 1024 / 1024 < 5;
  if (!isValidType) {
    ElMessage.error('只能上传 JPG/PNG 格式');
    return false;
  }
  if (!isValidSize) {
    ElMessage.error('图片大小不能超过5MB');
    return false;
  }
  return true;
}

const handleAvatarError = (error) => {
  console.error('上传失败:', error);
  ElMessage.error('头像上传失败: ' + (error.message || '服务器错误'));
}

const submitForm = async () => {
  try {
    const data = {
      username,
      avatarUrl: form.value.avatarUrl || '', // 确保总是有值
      realName: form.value.realName,
      gender: form.value.gender,
      birthDate: form.value.birthDate,
      phone: form.value.phone,
      email: form.value.email,
      address: form.value.address
    }

    console.log('提交的数据:', data); // 调试日志

    const response = await axios.post(BASE_URL+'/api/volunteer/updateUserInfo', data, {
      headers: {
        'Content-Type': 'application/json'
      }
    })

    if (response.status === 200) {
      ElMessage.success('保存成功');
    } else {
      ElMessage.error(response.data?.message || '保存失败');
    }
  } catch (error) {
    console.error('保存失败:', error);
    if (error.response) {
      if (error.response.status === 200 && error.response.data === '') {
        ElMessage.success('保存成功');
      } else {
        ElMessage.error(error.response.data?.message || '保存失败');
      }
    } else {
      ElMessage.error('网络错误，请检查连接');
    }
  }
}
</script>

<style scoped>
.basic-info {
  padding: 20px;
}
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 100px;
  height: 100px;
}
.avatar-uploader:hover {
  border-color: #409eff;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>